<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\News as NewsModel;
use think\Log;


class News extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function list()
    {
        if ($this->request->isOptions()) {
            exit();
        }

        $page = $this->request->get('page', 0);
        $page_size = $this->request->get('pageSize', config('api.page_size'));
        $category = $this->request->get('category', 0);

        $query = NewsModel::where('status', 1);
        if (!empty($category)) {
            $query = $query->where("FIND_IN_SET('$category', `category_ids`)");
        }
        $count = $query->count();

        $query = NewsModel::where('status', 1);
        if (!empty($category)) {
            $query = $query->where("FIND_IN_SET('$category', `category_ids`)");
        }
        $list = $query->order('weigh desc,createtime desc')
            ->field('id,title,summary,content,cover_image,createtime,updatetime')
            ->limit($page * $page_size, $page_size)
            ->select();

        $ret = [
            'entries' => collection($list)->toArray(),
            'count' => $count,
            'page' => $page,
            'domain' => $this->request->domain(),
        ];
        $this->success('返回成功', $ret);
    }

    public function detail()
    {
        if ($this->request->isOptions()) {
            exit();
        }

        $news_id = $this->request->get('newsId');
        $news = NewsModel::where('id', $news_id)
            ->where('status', 1)
            ->find();

        $related_news = NewsModel::where("FIND_IN_SET(`id`, '{$news->news_ids}')")
            ->field('id, title, summary')
            ->select();
        $related_news = collection($related_news)->toArray();

        $prev_news = NewsModel::where('createtime', '<', $news->createtime)
            ->order('createtime desc')
            ->field('id, title, summary')
            ->find();
        $next_news = NewsModel::where('createtime', '>', $news->createtime)
            ->order('createtime')
            ->field('id, title, summary')
            ->find();
        $t = var_export($prev_news, true);
        \think\Log::record(">>>prev_news: $t");
        if (empty($news)) {
            $this->error('未找到对应新闻', null, 404);
        }
        $ret = [
            'entry' => $news,
            'prevEntry' => $prev_news,
            'nextEntry' => $next_news,
            'relatedEntries' => $related_news,
            'domain' => $this->request->domain(),
        ];
        $this->success('返回成功', $ret);
    }
}
